/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web.service.Impl;

import java.util.List;
import web.Dao.impl.BookDAOImpl;
import web.enity.Book;
import web.exception.InsufficientStockException;
import web.service.BookService;
import web.Dao.BookDAO;

/**
 *
 * @author 10592
 */
public class BookServiceImpl implements BookService{
    BookDAO biz=new BookDAOImpl();
    @Override
    public List<Book> selectBooks(int pagenum, int rowcount) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        return biz.selectPage(pagenum, rowcount);
    }

    @Override
    public int selectCount() {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        return biz.selectCount();
    }

    @Override
    public boolean addBook(Book book) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        return biz.insert(book)==1 ? true : false;
    }

    @Override
    public Book getById(int bid) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        return biz.select(bid);
    }

    @Override
    public int checkStock(int bid, int num) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        Book b=biz.select(bid);
        if (b==null) {
            throw new InsufficientStockException();
        } else if (b.getStock()-num>=0) {
            return b.getStock()-num;
        }else{
            throw new InsufficientStockException();
        }
    }

    @Override
    public boolean decreaseStock(int bid, int num) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        boolean result=false;
        Book book=biz.select(bid);
        if (book!=null) {
            if (book.getStock()-num>0) {
                book.setStock(book.getStock()-num);
                biz.update(book);
                result=true;
            }
        }
        return result;
    }
    
}
